﻿using Bangle.BLL;
using Bangle.Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Phone_PhoneList : BasePage
{
    Sys_UserBLL user_bll = new Sys_UserBLL();
    UtilityBLL ubll = new UtilityBLL();
    T_PhoneTypeBLL type_bll = new T_PhoneTypeBLL();
    T_ClassificationBLL class_bll = new T_ClassificationBLL();
    T_SupplierBLL supplier_bll = new T_SupplierBLL();

    #region 属性
    public string pageIndex
    {
        get
        {
            return Request.QueryString["pageIndex"] == null ? "0" : Request.QueryString["pageIndex"].ToString();
        }
    }
    #endregion

    #region 加载
    protected void Page_Load(object sender, EventArgs e)
    {
        setUserControlStatus();
        if (!IsPostBack)
        {
            BindCheckBoxList();

            BindDropDownList();
        }
    }
    #endregion

    #region 检验用户权限
    private void setUserControlStatus()
    {
        //检验用户权限
        base.CheckUserPermission("002002");
        //this.btn_Add.Enabled = base.CheckUserPermissionOperation("002002", "Add");
    }
    #endregion

    #region 绑定数据
    private void BindCheckBoxList()
    {
        List<T_PhoneType> type_list = new List<T_PhoneType>();
        type_list = type_bll.GetModelList("Valid=1 order by PhoenTypeName");

        this.cbl_PhoneType.DataTextField = "PhoenTypeName";
        this.cbl_PhoneType.DataValueField = "PhoneTypeId";
        this.cbl_PhoneType.DataSource = type_list;
        this.cbl_PhoneType.DataBind();

        for (int i = 0; i < cbl_PhoneType.Items.Count; i++)
        {
            this.cbl_PhoneType.Items[i].Attributes.Add("data-id", this.cbl_PhoneType.Items[i].Value);
        }
    }


    private void BindDropDownList()
    {
        //类型
        List<T_Classification> class_list = class_bll.GetModelList("1=1");

        //屏幕
        int screen_id = class_list.Find(o => o.ClassificationCode == "Screen").ClassificationId;
        List<T_Classification> screen_list = class_list.FindAll(o => o.ParentId == screen_id);
        this.ddl_Screen.DataTextField = "ClassificationName";
        this.ddl_Screen.DataValueField = "ClassificationId";
        this.ddl_Screen.DataSource = screen_list;
        this.ddl_Screen.DataBind();
        this.ddl_Screen.Items.Insert(0, new ListItem("<全部>", ""));

        //芯片
        int ship_id = class_list.Find(o => o.ClassificationCode == "Chip").ClassificationId;
        List<T_Classification> chip_list = class_list.FindAll(o => o.ParentId == ship_id);
        this.ddl_Chip.DataTextField = "ClassificationName";
        this.ddl_Chip.DataValueField = "ClassificationId";
        this.ddl_Chip.DataSource = chip_list;
        this.ddl_Chip.DataBind();
        this.ddl_Chip.Items.Insert(0, new ListItem("<全部>", ""));

        //系列
        int series_id = class_list.Find(o => o.ClassificationCode == "Series").ClassificationId;
        List<T_Classification> series_list = class_list.FindAll(o => o.ParentId == series_id);
        this.ddl_Series.DataTextField = "ClassificationName";
        this.ddl_Series.DataValueField = "ClassificationId";
        this.ddl_Series.DataSource = series_list;
        this.ddl_Series.DataBind();
        this.ddl_Series.Items.Insert(0, new ListItem("<全部>", ""));

        List<T_Supplier> supplier_list = supplier_bll.GetModelList("Valid=1");
        supplier_list = supplier_list.OrderBy(o => o.SupplierName).ToList();
        this.ddl_SupplierId.DataTextField = "SupplierName";
        this.ddl_SupplierId.DataValueField = "SupplierId";
        this.ddl_SupplierId.DataSource = supplier_list;
        this.ddl_SupplierId.DataBind();
        this.ddl_SupplierId.Items.Insert(0, new ListItem("----请选择----", ""));
    }

    #endregion

    #region Ajex获取列表数据
    [WebMethod]
    public static AjexResponseModel GetGridDataHtml(int pageSize, int pageIndex
        , string RMB1, string RMB2, string USD1, string USD2, string PCS1, string PCS2
        , string Screen, string Chip, string Series
        , string SupplierId, string PhoneCode, string PartNo
        , string PhoneTypes, string OrderField
        )
    {
        AjexResponseModel result = new AjexResponseModel();
        #region 用户权限
        if (!CheckUserPermissionOperation2("002002", "View"))
        {
            result.msg = "没有用户权限，请联系管理员！";
        }
        #endregion

        string sWhere = " 1=1 ";
        #region 查询条件
        if (RMB1.Trim().Length > 0)
        {
            sWhere += " and RMB>=" + RMB1;
        }
        if (RMB2.Trim().Length > 0)
        {
            sWhere += " and RMB<=" + RMB2;
        }
        if (USD1.Trim().Length > 0)
        {
            sWhere += " and USD>=" + USD1;
        }
        if (USD2.Trim().Length > 0)
        {
            sWhere += " and USD<=" + USD2;
        }
        if (PCS1.Trim().Length > 0)
        {
            sWhere += " and PCS>=" + PCS1;
        }
        if (PCS2.Trim().Length > 0)
        {
            sWhere += " and PCS<=" + PCS2;
        }

        if (Screen.Trim().Length > 0)
        {
            sWhere += " and ScreenId=" + Screen;
        }
        if (Chip.Trim().Length > 0)
        {
            sWhere += " and ChipId=" + Chip;
        }
        if (Series.Trim().Length > 0)
        {
            sWhere += " and SeriesId=" + Series;
        }

        if (SupplierId.Trim().Length > 0)
        {
            sWhere += " and SupplierId = '" + SupplierId + "'";
        }
        if (PhoneCode.Trim().Length > 0)
        {
            sWhere += " and PhoneCode like '%" + PhoneCode + "%'";
        }
        if (PartNo.Trim().Length > 0)
        {
            sWhere += " and PartNo like '%" + PartNo + "%'";
        }
        if (PhoneTypes.Trim().Length > 0)
        {
            PhoneTypes = "'" + PhoneTypes.Replace(",", "','") + "'";
            //sWhere += " and PhoneType in (" + PhoneTypes + ")";
            sWhere += " and PhoneId in (select PhoneId from T_PhoneAndPhoneType where PhoneTypeId in (" + PhoneTypes + ")) ";
        }
        #endregion

        if (OrderField.Trim().Length > 0)
        {
            OrderField = OrderField.Trim() + ",";
        }

        try
        {
            UtilityBLL ubll = new UtilityBLL();
            int pCount = 0;
            DataTable dt = ubll.GetListByPage("View_T_Phone", "*", OrderField + "CreateTime", sWhere, pageSize, pageIndex, 1, out pCount);

            StringBuilder sHtml = new StringBuilder();

            #region 生成HTML
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sHtml.Append("<tr " + (i % 2 == 0 ? "" : "class='ht-grid-even'") + ">");
                sHtml.Append("<td class='td-select'><input type='checkbox' value='" + dt.Rows[i]["PhoneId"].ToString() + "'/></td>");
                sHtml.Append("<td>"
                    //+ "<div class='div-specification' title='" + dt.Rows[i]["AllPhoneTypeName"].ToString() + "' style='width:60px;'>"
                    + dt.Rows[i]["AllPhoneTypeName"].ToString().Replace(";", ";<br/>")
                    //+ "</div>"
                    + "</td>");
                sHtml.Append("<td>" + dt.Rows[i]["SupplierName"].ToString() + "</td>");
                sHtml.Append("<td>" + dt.Rows[i]["PhoneCode"].ToString() + "</td>");
                sHtml.Append("<td style='text-align: right'>" + Convert.ToDecimal(dt.Rows[i]["RMB"]).ToString("n2") + "</td>");
                sHtml.Append("<td>" + dt.Rows[i]["PartNo"].ToString() + "</td>");
                sHtml.Append("<td>" + dt.Rows[i]["ScreenName"].ToString() + "</td>");
                sHtml.Append("<td>" + dt.Rows[i]["ChipName"].ToString() + "</td>");
                sHtml.Append("<td>" + dt.Rows[i]["SeriesName"].ToString() + "</td>");
                string sTopPictureSrc = dt.Rows[i]["TopPictureSrc"].ToString();
                //sHtml.Append("<td style='width:100px'>" + (sTopPictureSrc.Length > 1 ? "<img src='" + sTopPictureSrc.ToString()
                //        + "' onclick='showPicture(\"" + sTopPictureSrc.ToString() + "\")' style='width:100px;height:80px;margin:5px;cursor:pointer;'/>" : "")
                //    + "</td>");showPicture
                sHtml.Append("<td style='width:100px'>" + (sTopPictureSrc.Length > 1 ? "<img src='" + sTopPictureSrc.ToString()
                        + "' onclick='showPicture(\"" + dt.Rows[i]["PhoneId"].ToString() + "\")' style='width:100px;height:80px;margin:5px;cursor:pointer;'/>" : "")
                    + "</td>");
                sHtml.Append("<td>");
                sHtml.Append("<div class='div-specification' title='" + dt.Rows[i]["SalePoint"].ToString() + "'>" + dt.Rows[i]["SalePoint"].ToString().Replace("\r", "").Replace("\n", "<br/>") + "</div>");
                sHtml.Append("</td>");
                sHtml.Append("<td style='text-align: right'>" + Convert.ToDecimal(dt.Rows[i]["USD"]).ToString("n2") + "</td>");
                sHtml.Append("<td style='text-align: right'>" + Convert.ToDecimal(dt.Rows[i]["PCS"]).ToString("n2") + "</td>");
                sHtml.Append("<td style='width:90px;'>");
                #region 操作
                string _sId = dt.Rows[i]["PhoneId"].ToString();
                if (CheckUserPermissionOperation2("002002", "View"))
                {
                    sHtml.Append(string.Format("<a href=\"javascript:showWindow('产品资料<查看>','PhoneEdit.aspx?Action={0}&id={1}')\">查看</a>&nbsp;&nbsp;",
                        "Detail", _sId));
                }
                if (CheckUserPermissionOperation2("002002", "Edit"))
                {
                    sHtml.Append(string.Format("<a href=\"javascript:showWindow('产品资料<编辑>','PhoneEdit.aspx?Action={0}&id={1}')\">编辑</a>&nbsp;&nbsp;",
                        "Modify", _sId));
                }
                if (CheckUserPermissionOperation2("002002", "Del"))
                {
                    sHtml.Append(string.Format("<a href=\"javascript:void(0)\" onclick=\"delGridData('{0}','{1}',this)\">删除</a>", "PhoneList.aspx/DelGridData", _sId));
                }
                #endregion
                sHtml.Append("</td>");
                sHtml.Append("</tr>");
            }
            #endregion

            result.gridHtml = sHtml.ToString();
            result.pageIndex = pageIndex;
            result.pageSize = pageSize;
            result.recordCound = pCount;
        }
        catch (Exception ex)
        {
            result.msg = "出现异常，请联系管理员！";
        }
        return result;
    }

    [WebMethod]
    public static string GetDropDownListDataHtml(string type)
    {
        T_ClassificationBLL class_bll = new T_ClassificationBLL();
        List<T_Classification> class_list = class_bll.GetModelList(" ParentId = (select top 1 ClassificationId from T_Classification where ClassificationCode='" + type + "')");

        class_list = class_list.OrderBy(o => o.ClassificationName).ToList();

        StringBuilder sHtml = new StringBuilder();
        sHtml.Append(string.Format("<option value=''>&lt;全部&gt;</option>"));
        foreach (T_Classification item in class_list)
        {
            sHtml.Append(string.Format("<option value='" + item.ClassificationId + "'>" + item.ClassificationName + "</option>"));
        }

        return sHtml.ToString();
    }

    [WebMethod]
    public static string DelGridData(string Id)
    {
        T_PhoneBLL bll = new T_PhoneBLL();
        string sMsg = "";

        try
        {
            bll.Delete(Guid.Parse(Id));
        }
        catch (Exception ex)
        {
            sMsg = "操作失败！";
        }
        return sMsg;
    }

    [WebMethod]
    public static List<PicModel> GetPictures(string Id)
    {
        T_PhonePictureBLL bll = new T_PhonePictureBLL();
        List<T_PhonePicture> list = new List<T_PhonePicture>();

        List<PicModel> pic_list = new List<PicModel>();
        try
        {
            list = bll.GetModelList(string.Format(" PhoneId='{0}' ", Id)).OrderByDescending(o => o.IsTop).ToList();

            foreach (var item in list)
            {
                PicModel pic = new PicModel();
                pic.href = item.Src;
                pic_list.Add(pic);
            }
        }
        catch (Exception ex)
        {

        }
        return pic_list;
    }
    #endregion

    #region 导出Excel

    protected void btn_Report_Click(object sender, EventArgs e)
    {
        //savePagerSelectedKey();

        string swhere = "''";
        //foreach (var item in pagerDic)
        //{
        //    swhere += ",'" + item.Key + "'";
        //}
        swhere = "  ltrim(PhoneId) in (''" + this.hf_PagerSelected.Value + ")";
        DataTable dt = ubll.GetListByPage("View_T_Phone", "PartNo,USD,PCS,SalePoint,TopPictureSrc", "PartNo", swhere);

        if (dt.Rows.Count < 1)
        {
            base.Alert("请选择你要导出的数据！");
            return;
        }

        WriteExcel(dt);
    }

    private void WriteExcel(DataTable dt)
    {
        string fileName = null; //文件名
        fileName = MapPath("/Report/ExcelTemp/PhoneReport.xls");

        string strOutputName = string.Format("Report_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssffff"));

        HSSFWorkbook wk = null;

        using (FileStream fs = File.OpenRead(fileName))   //打开myxls.xls文件
        {
            wk = new HSSFWorkbook(fs);   //把xls文件中的数据写入wk中
            ISheet sheet = wk.GetSheetAt(0);

            int baseRowNumber = 6;
            int baseRowCount = 16;

            #region 复制行样式
            for (int i = 0; i < baseRowCount * (dt.Rows.Count - 1); i++)
            {
                int _row = baseRowNumber + (i % baseRowNumber);
                sheet.CopyRow(baseRowNumber + i, baseRowNumber + baseRowCount + i);
            }
            #endregion

            #region 给单无格赋值
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string _PartNo = dt.Rows[i]["PartNo"].ToString();
                string _USD = Convert.ToDecimal(dt.Rows[i]["USD"].ToString()).ToString("n2");
                string _PCS = Convert.ToDecimal(dt.Rows[i]["PCS"].ToString()).ToString("n2");
                string _SalePoint = dt.Rows[i]["SalePoint"].ToString();
                string _TopPictureSrc = dt.Rows[i]["TopPictureSrc"].ToString();

                int _tempRowNumber = baseRowNumber + (i * baseRowCount);
                sheet.GetRow(_tempRowNumber).GetCell(0).SetCellValue(_PartNo);//PartNo
                //sheet.GetRow(_tempRowNumber).GetCell(1).SetCellValue(_TopPictureSrc);//Product Picture
                sheet.GetRow(_tempRowNumber).GetCell(3).SetCellValue(_USD);//USD
                sheet.GetRow(_tempRowNumber).GetCell(4).SetCellValue(_PCS);//PCS

                //Specification
                string[] strSalePoints = _SalePoint.Replace("\r\n", "\n").Split('\n');
                for (int ii = 0; ii < strSalePoints.Length && ii < baseRowCount; ii++)
                {
                    sheet.GetRow(_tempRowNumber + ii).GetCell(2).SetCellValue(strSalePoints[ii]);
                }

                //插入图片
                if (_TopPictureSrc.Length > 0)
                {
                    string _imgPath = MapPath(_TopPictureSrc);
                    ICell cell_pic = sheet.GetRow(_tempRowNumber).GetCell(1);
                    byte[] bytes = System.IO.File.ReadAllBytes(_imgPath);
                    int pictureIdx = wk.AddPicture(bytes, PictureType.JPEG);
                    IDrawing patriarch = sheet.CreateDrawingPatriarch();
                    HSSFClientAnchor anchor = new HSSFClientAnchor(10, 100, 1013, 100, cell_pic.ColumnIndex, cell_pic.RowIndex, cell_pic.ColumnIndex, cell_pic.RowIndex + baseRowCount - 1);
                    IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
                    //pict.Resize();
                }
            }
            #endregion

            #region 写入操作员信息
            Sys_User user = user_bll.GetModel(base.CurrentSession.UserID);
            string strUserInfo = string.Format("Contact: {0}      Skype: {1}       Email: {2}", user.Birthday, user.Phone, user.CertificateNo);
            sheet.GetRow(1).GetCell(1).SetCellValue(strUserInfo);
            #endregion
        }

        using (MemoryStream ms = new MemoryStream())
        {
            wk.Write(ms);
            ms.Flush();
            ms.Position = 0;

            ExportByWeb(ms, strOutputName);
        }
    }

    /// <summary>
    /// 用于Web导出
    /// </summary>
    /// <param name="dtSource">源DataTable</param>
    /// <param name="strHeaderText">表头文本</param>
    /// <param name="strFileName">文件名</param>
    public void ExportByWeb(MemoryStream ms, string strFileName)
    {
        byte[] bytes = new byte[(int)ms.Length];
        ms.Read(bytes, 0, bytes.Length);
        ms.Close();
        Response.ContentType = "application/vnd.ms-excel";
        //通知浏览器下载文件而不是打开
        Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8));
        Response.Buffer = false;
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }

    #endregion

    #region
    public class PicModel
    {
        public string href { get; set; }
    }
    #endregion
}
